package models

import (
	"fmt"
	"time"

	"gitee.com/lzqysoft/ga_wz_backend/libs/encrypt"

	"github.com/astaxie/beego/orm"
)

// Implement 项目实施记录
type Implement struct {
	Id            string    `orm:"column(id);pk"`
	Name          string    `orm:"column(name)"`
	CustId        string    `orm:"column(cust_id)"`
	CustName      string    `orm:"column(cust_name)"`
	UserId        string    `orm:"column(user_id);null"`
	Price         float64   `orm:"column(price)"`
	DiscountPrice float64   `orm:"column(discount_price)"`
	OrderId       string    `orm:"column(order_id);null"`
	OrderName     string    `orm:"column(order_name);null"`
	SoutId		 string  `orm:"column(sout_id)"`
	Plan          int       `orm:"column(plan)"`
	Really          int       `orm:"column(really)"`
	InstallType   int       `orm:"column(install_type)"` // 0, 未开始，1, 已调试，未安装，2，全部安装，3，部分安装
	InstallResult string    `orm:"column(install_result)"`
	Remark        string    `orm:"column(remark);null"`
	Status        int       `orm:"column(status)"`
	Isdelete      int       `orm:"column(isdelete)"`
	Ctime         time.Time `orm:"column(ctime);type(timestamp with time zone)"`
	Creater       string    `orm:"column(creater);null"`
	Utime         time.Time `orm:"column(utime);type(timestamp with time zone)"`
	Updater       string    `orm:"column(updater);null"`
}

func (t *Implement) TableName() string {
	return "yjk_implement"
}

func init() {
	orm.RegisterModel(new(Implement))
}


func AddImplementsFromOrderAndSoutAndOuts(order *Order, sout *Sout, user *User,plan int) (*Implement,error){
	imp := &Implement{}
	imp.SoutId = sout.Id
	imp.Id = encrypt.GetGuid()
	imp.Name = order.Name
	imp.CustId = order.CustId
	imp.CustName = order.CustName
	imp.UserId = order.UserId
	imp.Price = order.Price
	imp.DiscountPrice = order.DiscountPrice
	imp.OrderId = order.Id
	imp.OrderName = order.Name
	imp.Plan = plan
	imp.InstallType = 0
	imp.Status = 1
	imp.Isdelete = 0
	imp.Creater = user.Abbr
	imp.Updater = user.Abbr
	imp.Ctime = time.Now()
	imp.Utime = time.Now()
	o := orm.NewOrm()
	_, err := o.Insert(imp)
	if err != nil {
		return nil,err
	}

	return imp,err
}

// GetImplements 查询所有实施记录
func GetImplements() ([]Implement, error){
	imp := []Implement{}
	o := orm.NewOrm()
	_, err :=o.QueryTable(new(Implement)).Filter("Isdelete",0).OrderBy("-Ctime").All(&imp)
	return imp, err
}

func GetImplementById(id string) (v *Implement,err error) {
	o := orm.NewOrm()
	v = &Implement{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func UpdateImplementById(m *Implement) (err error) {
	o := orm.NewOrm()
	v := Implement{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}